using System;
using System.Data;
using System.DirectoryServices;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Dimok;
using Dimok.Data;
using Data;
using Data.DataSources;
public partial class Admin_StateFlow_Users_List : System.Web.UI.Page {
	bool UpdateDB { get { return chkUpdateDB.Checked; } }
	protected override void OnInit(EventArgs e) {
		base.OnInit(e);
		dsUsers.Selected += new ObjectDataSourceStatusEventHandler(dsUsers_Selected);
		grvUsers.SelectedIndexChanged += new EventHandler(grvUsers_SelectedIndexChanged);
		grvUsers.SearchChanged += new Dimok.Web.UI.GridViewEx.SearchChangedEventHandler(grvUsers_SearchChanged);
	}

	string FilterExpression { get { return ViewState["FilterExpression"] + ""; } set { ViewState["FilterExpression"] = value; } }

	void grvUsers_SearchChanged(string search) {
		dsUsers.FilterExpression = FilterExpression = search;
	}

	void dsUsers_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
		xmlUsers.InnerHtml = SQL.XmlInnerText((DataTable)e.ReturnValue);
	}

	void grvUsers_SelectedIndexChanged(object sender, EventArgs e) {
		txtNewUserName.Text = grvUsers.SelectedValue + "";
	}
	protected void Page_Load(object sender,EventArgs e) {
		if( !IsPostBack )
			Cache[dsUsers.CacheKeyDependency] = "User";

		ShowUsers();
		dsUsers.FilterExpression = FilterExpression;
		//xmlUsers.InnerHtml = SQL.XmlInnerText(dsUsers.SelectEx().Table);
	}

	protected void CreateUser(object sender, EventArgs e) {
		//throw new NotImplementedException("Must implement CreateUser");
		Create(txtNewUserName.Text, txtPassword.Text, selGroupName.SelectedValue);
		Cache.Remove(dsUsers.CacheKeyDependency);
		Cache[dsUsers.CacheKeyDependency] = "User";
		grvUsers.RequiresDataBinding = true;
	}
	public static void Create(string userName, string password, string groupDN) {
		string[] groupDNs = new string[] { groupDN };
		ADs.LDAP.CreateUser(Dimok.Config.ADS.ApplicationDN, userName, password, null, groupDNs, true, true);
		//grvUsers.RequiresDataBinding = true;
	}

	protected void RemUserFromGroup(object sender, EventArgs e) {
		var groupName = "LDAP://" + selGroupName.SelectedValue;
		try {
			ADs.LDAP.RemoveMemberFromGroup(txtNewUserName.Text, new DirectoryEntry(groupName));
			Cache.Remove(dsUsers.CacheKeyDependency);
			Cache[dsUsers.CacheKeyDependency] = "User";
			grvUsers.RequiresDataBinding = true;
		} catch (Exception exc) {
			exc.Data.Add("Group Name", groupName);
			throw new Exception("", exc); ;
		}
	}
	protected void GetUsers(object sender, EventArgs e) {
		try {
			ADsGroupDS dsGroups = ADs.LDAP.FindGroupsDS(Dimok.Config.ADS.AppGroupsDN, true);
			InsertGridView(dsGroups, "ALL Groups");
			ADsUser dsUser = ADs.LDAP.FindUsersDS(true,Dimok.Config.ADS.AppGroupsDN, true);
			InsertGridView(dsUser.th_AdsUser, "ALL Users");
			InsertGridView(dsUser.AdsGroup, "User -> Groups");

			if (UpdateDB) {
				dsUser.th_AdsUser.UserNameColumn.ColumnName = "sAMAccountName";
				dsUser.th_AdsUser.NameColumn.ColumnName = "DN";
				dsUser.th_AdsUser.NickColumn.ColumnName = "DisplayName";
				dsUser.Relations.Clear(); dsUser.AdsGroup.Constraints.Clear();
				dsUser.th_AdsUser.PrimaryKey = new DataColumn[] { };
				SQL.ExecuteNonQuery("DELETE FROM t_ADS_Login WHERE DomainContext=@DC", ADs.LDAP.domainContext);
				foreach (ADsUser.th_AdsUserRow drUser in dsUser.th_AdsUser)
					SQL.UpdateDataTable(drUser, SQL.ConnectionString, "SELECT sAMAccountName,DN,DisplayName,DomainContext FROM t_ADS_Login WHERE DomainContext=@DC AND sAMAccountName=@Login", ADs.LDAP.domainContext,drUser.UserName);

				foreach (ADsGroupDS.t_GroupRow drGroup in dsGroups.t_Group)
					SQL.UpdateDataTable(drGroup, SQL.ConnectionString, "SELECT SID,DN,DomainContext FROM t_ADS_Group WHERE DomainContext=@DC AND SID=@SID", ADs.LDAP.domainContext, drGroup.sid);

				ADsUser.AdsGroupDataTable dtUserGroups = new ADsUser.AdsGroupDataTable();
				new DataSet().Tables.Add(dtUserGroups);
				dtUserGroups.Columns.Add("DomainContext").DefaultValue = ADs.LDAP.domainContext;
				dtUserGroups.DataSet.Merge(dsUser.AdsGroup.Select("DN LIKE '%" + Dimok.Config.ADS.AppGroupsDN + "%'"));
				dtUserGroups.PrimaryKey = new DataColumn[] { };
				InsertGridView(dtUserGroups, "Logins to DB");
				dtUserGroups.UserNameColumn.ColumnName = "sAM_Login";
				dtUserGroups.sidColumn.ColumnName = "SID_Group";
				SQL.ExecuteNonQuery("DELETE FROM t_ADS_Login_Group WHERE DomainContext=@DC", ADs.LDAP.domainContext);
				foreach( ADsUser.AdsGroupRow drGroup in dtUserGroups )
				SQL.UpdateDataTable(drGroup, SQL.ConnectionString,
					"SELECT sAM_Login,SID_Group,DomainContext FROM t_ADS_Login_Group WHERE DomainContext=@DC AND sAM_Login = @Login AND SID_Group=@SID",
					ADs.LDAP.domainContext,drGroup.UserName,drGroup.sid);
			}
		} catch (Exception exc) {
			throw new Dimok.Exceptions.ASPException(exc);
		}

	}
	void InsertGridView(object dataSource) { InsertGridView(dataSource, ""); }
	void InsertGridView(object dataSource,string caption) {
		GridView gv = new GridView();
		gv.Caption = caption;
		Form.Controls.Add(gv);
		gv.DataSource = dataSource;
		gv.DataBind();
	}
	protected void DownloadUsers(object sender, EventArgs e) {
		DataView dv = new Data.DataSources.UsersDataSource().SelectEx().DefaultView;
		StringBuilder text = new StringBuilder();
		foreach (DataRowView row in dv)
			text.Append(row["User"]+","+row["Parent"]+ "\n");
		Response.AddHeader("content-disposition", "attachment; filename=\"" + "Dimok.txt" + "\"");
		Response.Write(text.ToString());
		//Response.SuppressContent = true;
		try {
			Response.End();
		} catch (System.Threading.ThreadAbortException) { }
	}

	void ShowUsers() {
			if (Regex.IsMatch(System.Threading.Thread.CurrentPrincipal.Identity.Name, "(dimon|help|boris)", RegexOptions.IgnoreCase)) {
			Literal ltr = new Literal();
			ltr.Text = "W:" + WindowsIdentity.GetCurrent().Name + "<br>T:" + System.Threading.Thread.CurrentPrincipal.Identity.Name;
			ltr.Text += "<br>AppGroupsDN:" + Dimok.Config.ADS.AppGroupsDN;
			Master.FindControl("form1").Controls.Add(ltr);
		}
	}

}
